# 导入必要的库和模块
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import pickle
from keras.datasets import mnist
from tqdm import tqdm  # tqdm库用于创建进度条
import numpy as np  # numpy库，用于数值计算，简称为np
import time  # time库，用于时间操作，例如延时

# 加载数字数据集
#digits = datasets.load_digits()
# 将数据集划分为训练集和测试集
#X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.2, random_state=42)

# 加载MNIST数据集
(X_train, y_train), (X_test, y_test) = mnist.load_data()

# 将图像数据展平为一维数组
X_train = X_train.reshape(X_train.shape[0], -1)
X_test = X_test.reshape(X_test.shape[0], -1)

# 初始化变量以存储最佳准确率，相应的k值和最佳knn模型
best_accuracy = 0
best_k = -1
best_knn = None

# 初始化一个列表以存储每个k值的准确率
accuracies = []

# 使用tqdm创建进度条，并遍历linspace_list中的元素
for k in tqdm(range(1, 41), desc="提示词: ", unit="每秒的单位"):
    # 尝试从1到40的k值，对于每个k值，训练knn模型，保存最佳准确率，k值和knn模型
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    accuracy = accuracy_score(y_test, y_pred)
    accuracies.append(accuracy)  # 更新accuracies列表
    if accuracy > best_accuracy:
        best_accuracy = accuracy
        best_k = k
        best_knn = knn
    # 在每次迭代中引入延时（例如0.1秒），以便进度条不会过快完成
    time.sleep(0.1)

# 将最佳KNN模型保存到二进制文件
with open('best_knn_model.pkl', 'wb') as f:
    pickle.dump(best_knn, f)

# 打印最佳准确率和相应的k值
print(f'最佳准确率: {best_accuracy}, 对应的k值: {best_k}')

# 绘制准确率变化图并保存为pdf文件
plt.figure(figsize=(12, 6))
plt.plot(range(1, 41), accuracies, color='blue', linestyle='dashed', marker='o', markerfacecolor='red', markersize=10)
plt.title('Accuracy Rate K Value')
plt.xlabel('K Value')
plt.ylabel('Accuracy')
plt.axvline(x=best_k, color='r', linestyle='--')
plt.text(best_k+1, best_accuracy, f'k={best_k}, accuracy={best_accuracy}', color='black')
plt.savefig('accuracy_plot.pdf')